package com.gr.labbackend.service.Impl.manage.events;

import com.alibaba.fastjson.JSONObject;
import com.gr.labbackend.mapper.EventMapper;
import com.gr.labbackend.model.dto.Event;
import com.gr.labbackend.service.manage.events.AddEventService;
import com.gr.labbackend.utils.GetUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class AddEventServiceImpl implements AddEventService {

    @Autowired
    private EventMapper eventMapper;

    @Override
    public JSONObject addEvent(Map<String, String> data) {
        JSONObject resp = new JSONObject();

        String title = data.get("title");
        String summary = data.get("summary");
        String htmlContent = data.get("htmlContent");
        String author = data.get("author");
        String source = data.get("source");

        if (title.isEmpty()) {
            resp.put("error_message", "标题不能为空");
            return resp;
        }

        if (htmlContent.isEmpty()) {
            resp.put("error_message", "文章内容不能为空");
            return resp;
        }

        if (author.isEmpty()) {
            resp.put("error_message", "作者不能为空");
            return resp;
        }

        if (source.isEmpty()) {
            resp.put("error_message", "出处不能为空");
            return resp;
        }

        if (title.length() > 100) {
            resp.put("error_message", "标题长度超出限制");
            return resp;
        }

        if (summary.length() > 100) {
            resp.put("error_message", "摘要长度超出限制");
            return resp;
        }

        if (author.length() > 50) {
            resp.put("error_message", "作者长度超出限制");
            return resp;
        }

        if (source.length() > 50) {
            resp.put("error_message", "出处长度超出限制");
            return resp;
        }

        Date now = new Date();
        Event event = new Event(null, GetUserUtil.getCurrentUser().getId(), title, summary, htmlContent, now, author, source);
        eventMapper.insert(event);
        resp.put("error_message", "success");

        return resp;
    }
}
